package com.scs.application.modules.wm.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.consts.GlobalConsts;
import com.scs.application.core.mvc.controller.FlowController;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.query.QueryContextHolder;
import com.scs.application.modules.sys.model.PageResult;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.wm.entity.WorkOrder;
import com.scs.application.modules.wm.entity.WorkOrderItem;
import com.scs.application.modules.wm.service.OutOrderItemService;
import com.scs.application.modules.wm.service.OutOrderService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.Serializable;

/**
 * <p>
 * 前端控制器R
 * </p>
 */
@RestController
@RequestMapping("/wm/out_order")
public class OutOrderController extends FlowController<OutOrderService, WorkOrder> {
    @Resource
    OutOrderItemService outOrderItemService;
    @Override
    @GetMapping("/page")
    public PageResult page() {
        QueryContext queryContext = QueryContextHolder.currentContext();

        queryContext.getWrapper().eq("direction", GlobalConsts.ORDER_DIRECTION_OUT);
        return super.page();
    }

    @GetMapping("/getOutOrder")
    public RestResult getOutOrder(@RequestParam("code") String code) {
        return RestResult.ok("ok",service.getOutOrder(code));
    }

    @GetMapping("getByUnicode")
    public RestResult getByUnicode(@RequestParam("uniqueCode") String code,@RequestParam("type") String type){
        return RestResult.ok("ok",service.getByUnicode(code,type));
    }

    private void fillEntity(WorkOrder entity) {
        entity.setCountDtl(outOrderItemService.count(Wrappers.<WorkOrderItem>query().select("id").eq("work_order_id",entity.getId())));
    }


    /**
     * 根据ID查找数据
     */
    @GetMapping("/find")
    public RestResult find(@RequestParam("id") Serializable id) {
        WorkOrder entity = service.getById(id);
        if (entity == null) {
            return RestResult.error("数据查询失败<br>可能所操作数据已被删除，请刷新后重新尝试操作");
        }
        fillEntity(entity);
        return RestResult.ok("获取数据成功", entity);
    }


    /**
     * 添加/更新数据
     */
    @PostMapping("/save")
    public RestResult saveItem(@Valid @RequestBody WorkOrder entity) {
        boolean isOk = service.saveOrUpdate(entity);
        if (!isOk) {
            return RestResult.error("数据保存失败");
        }
        fillEntity(entity);
        return RestResult.ok("数据保存成功", entity);
    }
}
